package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.TableUI;
import com.taotao.rop.database.domain.WechatUser;
import com.taotao.rop.database.domain.WechatUserAnalyse;
import com.taotao.rop.response.BaseResponse;
import com.taotao.wechat.business.Accesstoken;
import com.taotao.wechat.business.User;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/wechat/user")
public class WechatUserController {
    private Logger logger = Logger.getLogger(WechatUserController.class);
    private final String getList_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN";
    private final String getList_next_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Long pageSize = Long.parseLong(request.getParameter("pageSize"));
        Long pageNo = Long.parseLong(request.getParameter("pageNo"));

        String appId = request.getParameter("appId");
        String status = request.getParameter("status");

        WechatUser condition = new WechatUser();
        condition.setPageSize(pageSize);
        condition.setPageNo(pageNo);
        if (StringUtils.isNotBlank(appId) && !MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            condition.setAppId(appId);
        }
        if (StringUtils.isNotBlank(status) && !"all".equalsIgnoreCase(status)) {
            condition.setStatus(Integer.parseInt(status));
        }

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.list", "1.0");
        if (response.isSuccessful()){
            BaseResponse resp = response.getSuccessResponse();
            if (resp.getSuccess()){
                TableUI tableUI = new TableUI();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) resp.getData();
                tableUI.setTotal(resp.getMsg());
                tableUI.setRows(respData);
                return tableUI;
            } else {
                return resp;
            }
        } else {
            return response.getErrorResponse();
        }
    }

    private SimpleDateFormat shortDF = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping(value = "/analyse", method = RequestMethod.POST)
    @ResponseBody
    public Object analyse(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String appId = request.getParameter("appId");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        if (StringUtils.isBlank(startDate)) {
            startDate = "2014-01-01";
        }
        if (StringUtils.isBlank(endDate)) {
            endDate = shortDF.format(new Date());
        }

        Long start;
        try {
            Date theStart = shortDF.parse(startDate);
            start = new DateTime(theStart.getTime()).toDateTime(DateTimeZone.UTC).getMillis();
        } catch (ParseException e) {
            start = new DateTime(2014, 1, 1, 0, 0, DateTimeZone.UTC).getMillis();
            startDate = "2014-01-01";
        }
        Long end;
        try {
            Date theEnd = shortDF.parse(endDate);
            end = new DateTime(theEnd.getTime()).toDateTime(DateTimeZone.UTC).plusDays(1).getMillis();
        } catch (ParseException e) {
            end = DateTime.now(DateTimeZone.UTC).plusDays(1).getMillis();
            endDate = shortDF.format(new Date());
        }

        WechatUser condition = new WechatUser();
        condition.setTitle("【" + startDate + "】至【" + endDate + "】的关键指标");
        if (!MyRopClient.APP_ID.equalsIgnoreCase(appId)) {
            condition.setAppId(appId);
        }
        condition.setStartTime(start);
        condition.setEndTime(end);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.analyse", "1.0");
        if (response.isSuccessful()){
            return response.getSuccessResponse().getData();
        } else {
            return response.getErrorResponse();
        }
    }

    @RequestMapping(value = "/analyse/list", method = RequestMethod.POST)
    @ResponseBody
    public Object analyseList(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String appId = request.getParameter("appId");
        Long pageSize = Long.parseLong(request.getParameter("pageSize"));
        Long pageNo = Long.parseLong(request.getParameter("pageNo"));

        WechatUserAnalyse condition = new WechatUserAnalyse();
        condition.setAppId(appId);
        condition.setPageSize(pageSize);
        condition.setPageNo(pageNo);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.analyseList", "1.0");
        if (response.isSuccessful()){
            BaseResponse resp = response.getSuccessResponse();
            if (resp.getSuccess()){
                TableUI tableUI = new TableUI();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) resp.getData();
                tableUI.setTotal(resp.getMsg());
                tableUI.setRows(respData);
                return tableUI;
            } else {
                return resp;
            }
        } else {
            return response.getErrorResponse();
        }
    }

    @RequestMapping(value = "/getOldUsersFormWWW", method = RequestMethod.GET)
    @ResponseBody
    public String getOldUsersFormWWW(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String appKey = request.getParameter("appKey");
        Accesstoken accesstoken = new Accesstoken(appKey);

        getOldUser(appKey, accesstoken, null);
        return "同步成功";
    }

    private void getOldUser(String appKey, Accesstoken accesstoken, String nextOpenId) {
        String url = getList_url.replace("ACCESS_TOKEN", accesstoken.getAccesstoken());
        if (nextOpenId != null && nextOpenId.length() > 0) {
            url = getList_next_url.replace("ACCESS_TOKEN", accesstoken.getAccesstoken())
                    .replace("NEXT_OPENID", nextOpenId);
        }
        RestTemplate restTemplate = new RestTemplate();
        LinkedHashMap<String, Object> result = restTemplate.getForObject(url, LinkedHashMap.class);
        if (result.get("errcode") != null) {
            //errcode有值，说明出错了
            logger.info("get old users's error: " + result.get("errmsg"));
            return;
        }
        LinkedHashMap<String, Object> data = (LinkedHashMap<String, Object>) result.get("data");
        if (data != null) {
            List<String> openids = (List<String>) data.get("openid");
            User newUser = new User();
            for (String openId : openids) {
                newUser.insertUser(appKey, openId);
            }
            if (result.get("next_openid") != null) {
                String next_openid = result.get("next_openid").toString();
                if (next_openid.trim().length() > 0) {
                    getOldUser(appKey, accesstoken, next_openid);
                }
            }
        }
    }
}
